package cn.wxxyhw.Dao;

import cn.wxxyhw.Entity.Article;
import cn.wxxyhw.Util.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/**
 * 文章操作
 * @Author: 洪稳
 * @Date: 2019/6/3
 */
@Repository
public class ArticleDao {
    static QueryRunner queryRunner ;
    static {
        queryRunner = new QueryRunner(DataSourceUtil.getDataSource());
    }
    /**
     * 查询所有说说
     * @return
     */
    public List<Article> getAll() {
        List<Article> articles = null;
        String sql = "select * from article order by id desc";
        try {
            articles = queryRunner.query(sql, new BeanListHandler<>(Article.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return articles;
    }

    /**
     * 保存说说
     * @param article
     */
    public void save(Article article) {
        String sql = "insert into article(uname,image,date,content,dz,look,uid) values(?,?,?,?,?,?,?)";
        try {
            queryRunner.execute(sql,article.getUname(),
                    article.getImage(),
                    article.getDate(),
                    article.getContent(),
                    article.getDz(),
                    article.getLook(),
                    article.getUid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 浏览量加一
     */
    public void lookAddOne() {
        String sql = "update `article` set `look` =`look`+1;";
        try {
            queryRunner.update(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 点赞
     * @param id
     * @param option
     */
    public void dz(String id, String option) {
        String sql = "update `article` set `dz` =`dz`"+option+" where id = ?;";
        try {
            queryRunner.update(sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除说说
     * @param id
     */
    public void del(int id) {
        String sql = "delete from article where id = ?";
        try {
            queryRunner.update(sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
